//
//  C_SongLsit UICollectionViewLayout.m
//  音悦咖
//
//  Created by Best on 15/7/18.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "C_SongLsit UICollectionViewLayout.h"
#define ITEM_WIDTH  SCREEN_WIDTH - 180
#define ITEM_HEIGHT SCREEN_WIDTH - 180

#define ACTIVE_DISTANCE 120
#define ZOOM_FACTOR 0.3

@implementation C_SongLsit_UICollectionViewLayout

- (instancetype)init
{
    self = [super init];
    if (self) {
        
        self.itemSize = CGSizeMake(ITEM_WIDTH, ITEM_HEIGHT);
        self.scrollDirection = UICollectionViewScrollDirectionVertical;
        self.minimumLineSpacing = - 10;
        self.collectionView.pagingEnabled = YES;
        
    }
    return self;
}

- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
    return YES;
}

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
    NSArray *arr = [super layoutAttributesForElementsInRect:rect];
    
    CGRect visibleRect;
    
    visibleRect.origin = self.collectionView.contentOffset;
    visibleRect.size = self.collectionView.bounds.size;
    for (UICollectionViewLayoutAttributes *attributes in arr) {
        
        CGFloat distance = CGRectGetMidY(visibleRect) - attributes.center.y;
        CGFloat normakizedDistance = distance / ACTIVE_DISTANCE;
        if (ABS(distance) < ACTIVE_DISTANCE) {
            CGFloat zoom = 1 + ZOOM_FACTOR * (1 - ABS(normakizedDistance));
            attributes.transform3D = CATransform3DMakeScale(zoom, zoom, 1.0);
            attributes.zIndex = 1;
            
        }
    }
    return arr;
}

- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity
{
    CGFloat offsetAdjustment = MAXFLOAT;
    CGFloat horizontalCenter = proposedContentOffset.y + (CGRectGetHeight(self.collectionView.bounds) / 2.0);
    
    CGRect targetRect = CGRectMake(0.0, proposedContentOffset.y, self.collectionView.bounds.size.width, self.collectionView.bounds.size.height);
    
    NSArray *arr = [super layoutAttributesForElementsInRect:targetRect];
    
    
    
    for (UICollectionViewLayoutAttributes *layoutAttributes in arr) {
        CGFloat itemHorizontalCenter = layoutAttributes.center.y;
        if (ABS(itemHorizontalCenter - horizontalCenter) < ABS(offsetAdjustment)) {
            offsetAdjustment = itemHorizontalCenter - horizontalCenter;
        }
    }
    
    return CGPointMake(proposedContentOffset.x, offsetAdjustment + proposedContentOffset.y);
}

@end
